import datetime

from django.contrib import admin
from django.db.models import F
from django.db.models.functions import ExtractYear, ExtractMonth, ExtractWeek

from analysis.models import *
from oa.admin import SimpleModelAdmin, AutoUpdateUserModelAdmin
from tb3.utils import queryset_export_excel


@admin.register(KingdeeProductInfo)
class KingdeeProductInfoAdmin(SimpleModelAdmin):
    list_display = ['pk', 'product_code', 'product_name', 'package', 'unit']
    list_display_links = ['pk', 'product_code']


@admin.register(StorageProductInfo)
class StorageProductInfoAdmin(SimpleModelAdmin):
    list_display = [
        'pk', 'product_name', 'package', 'unit', 'package_group', 'is_show', 'need_statistic']
    list_display_links = ['pk', 'product_name', 'package', 'unit']
    search_fields = ['product_name', 'package', 'unit']
    list_editable = ['package_group', 'is_show']
    autocomplete_fields = ['package_group']
    list_filter = ['is_show', 'is_linked', 'package_group', 'need_statistic']


@admin.register(SalesRecordUpload)
class SalesRecordUploadAdmin(AutoUpdateUserModelAdmin):
    list_display = [
        'pk', 'file_name', 'file', 'total_count', 'created_count', 'updated_count', 'failed_count', 'is_imported',
    ]
    list_display_links = ['pk', 'file_name']
    search_fields = ['file_name']
    list_filter = ['is_imported']
    readonly_fields = [
        'file_name', 'total_count', 'created_count', 'updated_count', 'failed_count',
        'is_imported', 'created_by', 'updated_by'
    ]


@admin.register(SalesRecord)
class SalesRecordAdmin(SimpleModelAdmin):
    date_hierarchy = 'sales_date'
    list_display = [
        'pk', 'sales_date', 'sales_order', 'salesman', 'customer',
        'product_name', 'product_code', 'product_model', 'unit',
        'amount', 'unit_price', 'income', 'cost', 'sales_cost'
    ]
    list_display_links = [
        'pk', 'sales_date', 'sales_order',
    ]
    search_fields = ['sales_order', 'salesman', 'product_name', 'customer']
    list_filter = [
        'related_product_info', 'related_customer', 'sales_channel', 'sales_date',
        'related_customer__related_salesman', 'commission_payed', 'has_cost', 'has_sales_cost'
    ]

    def save_execl_1(self, request, queryset):
        queryset = queryset.exclude(
            related_customer__need_statistic=False
        ).exclude(
            related_product_info__need_statistic=False
        ).annotate(
            year=ExtractYear('sales_date'),
            month=ExtractMonth('sales_date'),
            week=ExtractWeek('sales_date')
        ).order_by('sales_date')
        filename = 'media/{0}_{1}.xls'.format('sales_record', datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        headers = [
            'ID', '日期', '年', '月', '周', '仓库', '产品原始名称', '包装名称', '数量', '单价', '销售收入',
            '单位生产成本', '生产成本',
            '单位出厂成本', '出厂成本',
            '销售人员-单子', '销售人员-客户关联',
            '客户', '客户类别', '渠道']
        columns = [
            'pk', 'sales_date', 'year', 'month', 'week', 'warehouse', 'product_name',
            'related_product_info__package_group__name',
            'amount', 'unit_price', 'income', 'related_product_info__package_group__reference_cost', 'cost',
            'related_product_info__package_group__sales_cost', 'sales_cost',
            'salesman', 'related_customer__related_salesman__full_name',
            'customer', 'related_customer__customer_level__level_name', 'sales_channel']
        return queryset_export_excel(queryset, headers, columns, filename)

    save_execl_1.short_description = "包装组合导出"

    def save_execl_2(self, request, queryset):
        queryset = queryset.exclude(
            related_customer__need_statistic=False
        ).exclude(
            related_product_info__need_statistic=False
        ).annotate(
            year=ExtractYear('sales_date'),
            month=ExtractMonth('sales_date'),
            week=ExtractWeek('sales_date'),
            group_code=F('related_product_info__package_group__code'),
            group_name=F('related_product_info__package_group__name'),
            pack_code=F('related_product_info__package_group__packageitem__product_package__code'),
            pack_name=F('related_product_info__package_group__packageitem__product_package__name'),
            package_unit=F('related_product_info__package_group__packageitem__product_package__package_unit__display'),
            product_real_name=F('related_product_info__package_group__packageitem__product_package__product_name__name'),
            category_name=F('related_product_info__package_group__packageitem__product_package__product_name__product_category__name'),
            pack_amount=F('related_product_info__package_group__packageitem__amount'),
        ).order_by('sales_date')
        filename = 'media/{0}_{1}.xls'.format('sales_record_detail', datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        headers = [
            'ID', '日期', '年', '月', '周', '仓库', '产品原始名称',
            '组合编号', '组合名称', '产品编号', '产品包装名称', '包装数量', '产品名称', '产品归类',
            '包装规格', '出库数量', '客户', '客户类别', '渠道']
        columns = [
            'pk', 'sales_date', 'year', 'month', 'week', 'warehouse', 'product_name',
            'group_code', 'group_name', 'pack_code', 'pack_name', 'pack_amount',
            'product_real_name', 'category_name',
            'package_unit', 'amount', 'customer', 'related_customer__customer_level__level_name', 'sales_channel']
        return queryset_export_excel(queryset, headers, columns, filename)

    save_execl_2.short_description = "拆分导出"

    def update_cost(self, request, queryset):
        for qs in queryset:
            qs.save()

    update_cost.short_description = "更新成本"

    def update_commission_payed(self, request, queryset):
        queryset.update(commission_payed=True)

    update_commission_payed.short_description = "发放提成"

    actions = [save_execl_1, save_execl_2, update_cost, update_commission_payed]


@admin.register(StorageCalculate)
class StorageCalculateAdmin(SimpleModelAdmin):
    list_display = ['pk', 'hz_file', 'sh_file', 'recorded_at', 'is_imported']
    list_display_links = ['pk', 'recorded_at', 'is_imported']
    date_hierarchy = 'recorded_at'


@admin.register(Storage)
class StorageAdmin(SimpleModelAdmin):
    list_display = [
        'pk', 'related_calculate', 'order_index', 'file_index',
        'warehouse', 'product_category', 'product_code', 'product_name', 'package', 'unit',
        'current_storage', 'related_product_info']
    list_display_links = ['pk', 'order_index', 'file_index', 'product_code', 'product_name']
    search_fields = ['product_code', 'product_name']
    list_filter = ['related_calculate', 'file_index']